<?php

namespace addons\shopro\controller;

use addons\shopro\exception\Exception;
use app\common\model\VipModel;
use app\common\model\VipOrderModel;

class Vip extends Base
{

    protected $noNeedLogin = ['getVipList', 'getVipDetail'];
    protected $noNeedRight = ['*'];

    /**
     * 获取vip列表
     * @param VipModel $vipModel
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getVipList()
    {
        $vipModel = new VipModel();
        $list     = $vipModel->where(['status' => 1])
            ->field('status,sort,create_time,update_time', true)
            ->select();

        return json([
            'code' => 1,
            'msg'  => '获取成功',
            'data' => [
                'vipList' => $list
            ]
        ]);
    }

    /**
     * vip详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getVipDetail()
    {
        $vipModel = new VipModel();
        $id       = $this->request->param('id');

        if (empty($id)) {
            return json([
                'code' => 401,
                'msg'  => '参数错误',
            ]);
        }

        $detail = $vipModel->where(['id' => $id])
            ->field('status,sort,create_time,update_time', true)
            ->find();

        return json([
            'code' => 1,
            'msg'  => '获取成功',
            'data' => [
                'detail' => $detail
            ]
        ]);
    }

    /**
     * vip购买
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function buyVip()
    {
        $vipModel = new VipModel();
        $id       = $this->request->param('id');
        $num      = $this->request->param('num');

        if (empty($id) || empty($num) || floor($num) <= 0) {
            return json([
                'code' => 401,
                'msg'  => '参数错误',
            ]);
        }

        $detail = $vipModel->where(['id' => $id])
            ->field('status,sort,create_time,update_time', true)
            ->find();

        if (empty($detail)) {
            return json([
                'code' => 402,
                'msg'  => '您要购买的VIP不存在',
            ]);
        }

        $user = $this->auth->getUser();
        // 创建订单
        $vipOrderModel       = new VipOrderModel();
        $data                = [];
        $data['vid']         = $detail->id;
        $data['num']         = $num;
        $data['user_id']     = $user['id'];
        $data['order_no']    = $vipOrderModel->getOrderNo();
        $data['pay_price']   = bcmul($detail->price, $num, 2);
        $data['create_time'] = time();
        $id                  = $vipOrderModel->insertGetId($data);

        if (!empty($id)) {
            try {
                $oauth      = \addons\shopro\model\UserOauth::where([
                    'user_id'  => $user['id'],
                    'provider' => 'Wechat',
                    'platform' => 'wxMiniProgram'
                ])->find();
                $notify_url = $this->request->root(true) . '/addons/shopro/pay/notifyvip/payment/wechat/platform/wxMiniProgram';
                $pay        = new \addons\shopro\library\PayService('wechat', 'wxMiniProgram', $notify_url);
                $result     = $pay->create([
                    'out_trade_no' => $data['order_no'],
                    'total_fee'    => $data['pay_price'],
                    'openid'       => $oauth->openid,
                    'body'         => '会员vip购买'
                ]);
            } catch (\Exception $e) {
                $this->error("支付配置错误：" . $e->getMessage());
            }

            return json([
                'code' => 1,
                'msg'  => '下单成功',
                'data' => [
                    'wxPay' => $result
                ]
            ]);
        } else {
            return json([
                'code' => 400,
                'msg'  => '购买vip失败',
            ]);
        }
    }

    /**
     * 获取用户vip订单列表
     * @return \think\response\Json
     */
    public function getUserVipOrderList()
    {
        $user          = $this->auth->getUser();
        $vipOrderModel = new VipOrderModel();
        $page          = $this->request->param('page', 1);
        $status        = $this->request->param('status', 0);
        $result        = $vipOrderModel->getLists([
            'status'  => $status,
            'user_id' => $user['id'],
        ], 20, $page, 'a.*,b.nickname,b.avatar,b.mobile');

        if (!empty($result['list'])) {
            foreach ($result['list'] as &$v) {
                $v['pay_time']     = !empty($v['pay_time']) ? date('Y-m-d H:i', $v['pay_time']) : '';
                $v['expires_time'] = !empty($v['expires_time']) ? date('Y-m-d H:i', $v['expires_time']) : '';
                $v['create_time']  = !empty($v['create_time']) ? date('Y-m-d H:i', $v['create_time']) : '';
            }
        }

        return json([
            'code' => 1,
            'msg'  => '获取成功',
            'data' => $result
        ]);
    }

    /**
     * 支付vip订单
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function payOrder()
    {
        $vipOrderModel = new VipOrderModel();
        $id            = $this->request->param('id');

        if (empty($id)) {
            return json([
                'code' => 401,
                'msg'  => '参数错误',
            ]);
        }

        $detail = $vipOrderModel->getItem($id);

        if (empty($detail)) {
            return json([
                'code' => 402,
                'msg'  => '您要支付的订单不存在',
            ]);
        }
        if ($detail->status == 1) {
            return json([
                'code' => 403,
                'msg'  => '此订单已支付过了',
            ]);
        }
        try {
            $orderNo    = $vipOrderModel->getOrderNo();
            $user       = $this->auth->getUser();
            $oauth      = \addons\shopro\model\UserOauth::where([
                'user_id'  => $user['id'],
                'provider' => 'Wechat',
                'platform' => 'wxMiniProgram'
            ])->find();
            $notify_url = $this->request->root(true) . '/addons/shopro/pay/notifyvip/payment/wechat/platform/wxMiniProgram';
            $pay        = new \addons\shopro\library\PayService('wechat', 'wxMiniProgram', $notify_url);
            $result     = $pay->create([
                'out_trade_no' => $orderNo,
                'total_fee'    => $detail->pay_price,
                'openid'       => $oauth->openid,
                'body'         => '会员vip购买'
            ]);

            // 更新订单
            $vipOrderModel->update([
                'id'       => $id,
                'order_no' => $orderNo
            ]);

            return json([
                'code' => 1,
                'msg'  => '获取支付信息成功',
                'data' => [
                    'wxPay' => $result
                ]
            ]);
        } catch (\Exception $e) {
            $this->error("支付配置错误：" . $e->getMessage());
        }
    }

}